package com.crazy.cloud.security.security;

import com.crazy.cloud.common.utils.PasswordUtil;
import com.crazy.cloud.security.biz.service.UserInfoService;
import com.crazy.cloud.user.api.dto.UserDTO;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

/**
 * @program: crazy-cloud
 * @description: 认证provider
 * @author: CrazyMan
 * @create: 2018/9/27 下午5:37
 **/
@Slf4j
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserInfoService userInfoService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        Preconditions.checkArgument(StringUtils.isNotBlank((String) authentication.getPrincipal()), "用户名不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank((String) authentication.getCredentials()), "密码不能为空");
        UserDTO user = loadUser((String) authentication.getPrincipal());
        if (!PasswordUtil.loginPass((String) authentication.getCredentials(), user.getPassword(), user.getSalt())) {
            log.error("登录密码错误,登录名称：{}", (String) authentication.getCredentials());
            throw new AuthenticationServiceException("用户名或密码错误");
        }
        return new UsernamePasswordAuthenticationToken(user.getClientId(), user.getPassword(),
            AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    private UserDTO loadUser(String loginName) {
        UserDTO user = userInfoService.getUserByUsername(loginName);
        if (null == user) {
            user = userInfoService.getUserByPhoneNo(loginName);
        }
        if (null == user) {
            user = userInfoService.getUserByEmail(loginName);
        }
        if (null == user) {
            log.error("{} 登录 用户不存在", loginName);
            throw new AuthenticationServiceException("用户名或密码错误");
        }
        return user;
    }
}
